<script setup lang="ts">
import {inject, ref} from 'vue';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import emitter from '@/utils/emitter.ts'
import useUserStore from '@/store/modules/user.ts'
import commentApi from '@/api/comment.ts'
const userStore = useUserStore()
dayjs.extend(relativeTime);

type Comment = Record<string, string>;
const comments = ref<Comment>([]);
const submitting = ref<boolean>(false);
const value = ref<string>('');
// 文章id
const articleId = inject('articleId')
//提交
const handleSubmit = async () => {
  if (!value.value) {
    return;
  }
  const result = await commentApi.saveComment({
    targetId: articleId,
    parentId: null,
    content: value.value,
    level: 1,
    url: window.location.href
  })
  if (result.code == 200) {
    comments.value =  {
        id: result.data.id,
        author: result.data.user.nickname,
        avatar: result.data.user.avatar,
        content: result.data.content,
        datetime: result.data.createTime,
      }
  }
  submitting.value = true;
  setTimeout(() => {
    submitting.value = false;
    // comments.value = [
    //   {
    //     author: userStore.userInfo.nickname,
    //     avatar: userStore.userInfo.avatar,
    //     content: value.value,
    //     datetime: dayjs().fromNow(),
    //   },
    //   ...comments.value,
    // ];
    value.value = '';
    console.log(comments.value)
    emitter.emit('comments', comments.value)
  }, 1000);
};

</script>

<template>
  <div class="comment-box">
    <a-comment>
      <template #avatar>
        <a-avatar :src="userStore.userInfo.avatar" alt="Han Solo" />
      </template>
      <template #content>
        <a-form-item>
          <a-textarea v-model:value="value" :rows="4" />
        </a-form-item>
        <a-form-item>
          <a-button html-type="submit" :loading="submitting" type="primary" @click="handleSubmit">
            提交评论
          </a-button>
        </a-form-item>
      </template>
    </a-comment>
  </div>
</template>
<style scoped lang="scss">

</style>
